import { getHospitals, addHospital, modifyHospital } from "@/api/reservations"

const hospital = {
  namespaced: true,
  state: {
    hospitals: null,
    mode: "view", // "add", "modify"
    currentNotice: {}
  },

  getters: {
    getCurrentNotice: (state) => {
      return state.currentNotice;
    },
    defaultHospital(state) {
      if (state.hospitals==null || state.hospitals.length===0) {
          return null;
      }
      else {
          return state.hospitals[0];
      }
  }
  },

  mutations: {
    SET_DATA: (state, payload) => { // 从localStorage同步
      console.log("SET_DATA", payload);
      state.mode = payload.mode;
      state.allAppointments = null;
      state.currentNotice = payload.currentNotice;
    },        
    SET_HOSPITAL: (state, hospitals) => {
      console.log("SET_HOSPITAL", hospitals);
      state.hospitals = hospitals;
    },
    ADD_HOSPITAL: (state, hospital) => {
      state.hospitals.push(hospital);
    },
    UPDATE_HOSPITAL: (state, hospital)=>{
      for(var i=0;i<state.hospitals.length;i++) {
        var element = state.hospitals[i];
        if (element.hospitalId == hospital.hospitalId) {
          state.hospitals.splice(i, 1, hospital);
          break;
        }
      }
    },
    SET_MODE: (state, mode)=>{
      state.mode = mode;
    },
    setNotice: (state, payload) => {
      state.currentNotice = payload;
    }
  },

  actions: {
    refresh_hospital: async (context)=>{
      var data = await getHospitals();
      context.commit("SET_HOSPITAL", data);
    },
    add_hospital: (context, hospitalInfo)=>{
      addHospital(hospitalInfo)
      .then(res=>{
        context.commit("ADD_HOSPITAL", res);
        context.commit("SET_MODE", "view");
      })
    },
    modify_hospital: (context, hospitalInfo)=>{
      modifyHospital(hospitalInfo)
      .then(res=>{
        console.log(res);
        context.commit("SET_MODE", "view");
        context.commit("UPDATE_HOSPITAL", res);
      })
    }
  }

};

export default hospital;
